package xiaobange.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理
 */
@ControllerAdvice(annotations = {RestController.class , Controller.class})
@ResponseBody//把方法的返回数据封装成JSON数据
@Slf4j
public class CatchException {

    /**
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> GetException(SQLIntegrityConstraintViolationException exception){
        if (exception.getMessage().contains("Duplicate entry")){
            String[] s = exception.getMessage().split(" ");
            String msg = s[2] + "已存在";
            log.info("用户名重复了：{}",s[2]);
            return R.error(msg);
        }
        return R.error("未知错误！");
    }

    /**
     * 自定义业务异常
     * @param exception
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> GetException(CustomException exception){
        //返回结果给前端页面
        return R.error(exception.getMessage());
    }

}
